package com.bojiu.lawsearch.lawsearch.util;

import com.bojiu.lawsearch.lawsearch.mapper.LabelMapper;
import com.bojiu.lawsearch.lawsearch.model.Attachment;
import com.bojiu.lawsearch.lawsearch.model.Label;
import com.bojiu.lawsearch.lawsearch.model.Rule;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author afdiao
 * @Date 2020/2/26 22:34
 */
@Component
@Slf4j
public class FileHandler {



    /**
     * 上传后生成本地文件
     *
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public Attachment createFile(MultipartFile multipartFile) throws Exception {
        String str = multipartFile.getOriginalFilename();
        String subString = str.substring(str.lastIndexOf("."));
        String storeName = UtilTools.createUUid() + subString;
        //判读当前目录是否存在
        checkPath();
        FileOutputStream outputStream = new FileOutputStream(Constances.STORE_URL + storeName);
        outputStream.write(multipartFile.getBytes());
        outputStream.flush();
        outputStream.close();
        Attachment attachment = new Attachment();
        attachment.setStoreName(storeName);
        attachment.setFileName(str);
        return attachment;
    }


    /**
     * 读取word文件
     *
     * @param multipartFile
     * @return
     */
    public String readWord(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        StringBuffer stringBuffer = new StringBuffer();
        try {
            if (filename.endsWith(".doc")) {
                InputStream inputStream = multipartFile.getInputStream();
                WordExtractor wordExtractor = new WordExtractor(inputStream);
                for (String message : wordExtractor.getParagraphText()) {
                    log.debug("message is :{}", message);
//                    Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
//                    Matcher matcher = pattern.matcher(message);
//                    String newMess = matcher.replaceAll("");
                    stringBuffer.append(message);
                }
                inputStream.close();
            } else if (filename.endsWith(".docx")) {
                //创建一个临时文件
                String tempName = UtilTools.createUUid() + ".docx";
                checkPath();
                File tempFile = new File(Constances.STORE_URL + tempName);
                FileCopyUtils.copy(multipartFile.getBytes(), tempFile);
                OPCPackage opcPackage = POIXMLDocument.openPackage(Constances.STORE_URL + tempName);
                XWPFDocument xwpfDocument = new XWPFDocument(opcPackage);
                List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    String text = paragraph.getText();
//                    Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");
//                    Matcher matcher = pattern.matcher(text);
//                    String newMess = matcher.replaceAll("");
                    stringBuffer.append(text);
                }
                tempFile.delete();
            } else {
                log.error("文件格式错误");
            }
            log.debug("word 解析成功!!");
            return stringBuffer.toString();
        } catch (Exception e) {
            log.error("error to read word,error is:{}", e);
            return "error";
        }
    }

    /**
     * 创建excel文件
     *
     * @param string
     * @return
     * @throws Exception
     */
    public String createExcel(String string) throws Exception {
        String[] split = string.split(Constances.SPLIT_MARK);
        //创建excel
        String fileName = UtilTools.createUUid() + ".xlsx";
        checkPath();
        File file = new File(Constances.STORE_URL + fileName);
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("明细");
        Row firstRow = sheet.createRow(0);
        //创建第一行信息
        Cell firstRowCell = null;
        firstRowCell = firstRow.createCell(0);
        firstRowCell.setCellValue("条例");
        firstRowCell = firstRow.createCell(1);
        firstRowCell.setCellValue("固定标签");
        firstRowCell = firstRow.createCell(2);
        firstRowCell.setCellValue("手动标签");
        for (int i = 0; i < split.length; i++) {
            Row row = sheet.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(split[i]);
        }
        OutputStream outputStream = new FileOutputStream(file);
        workbook.write(outputStream);
        outputStream.close();
        log.debug("生成文件成功");
        return fileName;
    }

    private void checkPath() {
        File file = new File(Constances.STORE_URL);
        if (!file.exists()) {
            file.mkdir();
        }
    }


}
